package com.example.user.service.impl;

import com.example.common.entity.Result;
import com.example.common.entity.sys.SysDept;
import com.example.common.entity.sys.SysRole;
import com.example.common.exception.NoResultException;
import com.example.user.entity.vo.RoleVo;
import com.example.user.entity.vo.UserVo;
import com.example.user.feign.RemoteRoleDeptService;
import com.example.user.mapper.SysUserMapper;
import com.example.user.service.ISysUserService;
import com.google.common.collect.Lists;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author cc
 * @since 2022-08-12
 */
@Service
public class SysUserServiceImpl implements ISysUserService {

    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private RemoteRoleDeptService remoteRoleDeptService;

    /**
     * 获取所有用户
     * @return
     */
    @Override
    public List<UserVo> getUsers() {
        //查询所有用户信息
        List<UserVo> userVos = userMapper.getUsers();
        if (CollectionUtils.isEmpty(userVos)) {
            throw new NoResultException();
        }
        userVos.forEach(userVo -> {
            //调用角色部门服务查询角色信息
            Result<List<SysRole>> sysRolesResult = remoteRoleDeptService.getRolesByUserId(userVo.getUserId());
            List<SysRole> sysRoles = sysRolesResult.getData();
            List<RoleVo> roleVos = Lists.newArrayListWithCapacity(sysRoles.size());
            sysRoles.forEach(sysRole -> {
                //调用角色部门服务查询部门信息
                Result<List<SysDept>> sysDeptsResult = remoteRoleDeptService.getDeptsByRoleId(sysRole.getRoleId());
                RoleVo roleVo = new RoleVo();
                BeanUtils.copyProperties(sysRole, roleVo);
                roleVo.setDepts(sysDeptsResult.getData());
                roleVos.add(roleVo);
            });
            userVo.setRoles(roleVos);
        });
        return userVos;
    }
}
